export default {
  namespaced:true,
  actions:{
    addgoods(context,value){
      const index=context.state.cart.findIndex(x=>x.goods_id===value.goods_id)
      if(index===-1) context.commit('addToCart',value)
      else context.commit('addCartNumber',index)
    }
  },
  mutations:{
    addToCart(state,value){
      state.cart.push(value)
      this.commit('m_cart/saveToStorage')
    },
    addCartNumber(state,index){
      state.cart[index].goods_count++
      this.commit('m_cart/saveToStorage')
    },
    updateGoodsState(state,goods){
      const findResult=state.cart.find(x=>x.goods_id===goods.goods_id)
      if('goods_state' in goods) findResult.goods_state=goods.goods_state
      if('goods_count' in goods) findResult.goods_count=goods.goods_count
      this.commit('m_cart/saveToStorage')
    },
    swipeActionClickHandler(state,goods){
      state.cart=state.cart.filter(x=>x.goods_id!==goods.goods_id)
      this.commit('m_cart/saveToStorage')
    },
    updateAllGoodsState(state, newState) {
      // 循环更新购物车中每件商品的勾选状态
      state.cart.forEach(x => x.goods_state = newState)
      // 持久化存储到本地
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    }
  },
  state:{
        // 购物车的数组，用来存储购物车中每个商品的信息对象
        // 每个商品的信息对象，都包含如下 6 个属性：
        // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  },
  getters:{
    total(state){
      // let c=0
      // state.cart.forEach(goods=>c+=goods.goods_count)
      // return c
      return state.cart.length
    },
    checkedCount(state){
      return state.cart.filter(x=>x.goods_state).length
    },
    checkedGoodsAmount(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
    }
  }
}